import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Radio,
  Badge,
  Divider,
} from 'antd';
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { enquireScreen, unenquireScreen } from 'enquire-js';

import styles from './TableList.less';

Date.prototype.Format = function (fmt) { //author: meizz
  var o = {
    "Y+": this.getUTCFullYear(),
    "M+": this.getMonth() + 1, //月份
    "D+": this.getDate(), //日
    "H+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'processing','processing','success','error'];
const status = ['未发布',"等待发布","发布中", '已使用',"发布失败"];

let isMobile;
enquireScreen(b => {
  isMobile = b;
});

@connect(({ rule, loading }) => ({
  rule,
  loading: loading.models.rule,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    type:"",
  };

  componentDidMount() {
    this.refresh()
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'rule/fetchTasks',
      payload: params,
    });
  };


  refresh = () => {
    const { dispatch } = this.props;
    const { rule: { tasks:{ list, page,page_size }}} = this.props;

    dispatch({
      type: 'rule/fetchTasks',
      payload: {
        page:page,
        size:page_size,
      },
    });
  }

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'rule/fetchTasks',
        payload: values,
      });
    });
  };



  renderForm() {
    return this.state.expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  handleChange = value => {
    console.log(`selected ${value}`);
    if (value == 'all'){
      this.state.type = ""
    } else{
      this.state.type = value
    }
    this.refresh()
  }

  republish = task => {
    this.props.dispatch({
      type: 'rule/republish',
      payload: {
        id: task.id,
      },
      callback: () => {
        message.success('操作成功');
        this.refresh()
      }
    })
  }
  
  praseType = value => {
    switch(value){
      case 'kb_news_bagua':
        return "娱乐"
      case 'kb_news_sports':
        return "运动"
      case 'kb_news_laugh':
        return "搞笑"
      case 'kb_news_hotnews':
        return "热文"
      case 'kb_news_sex':
        return '情感'
    }
  }
  
  praseDate = value => {
    var date = new Date(value)
    date.setHours(date.getHours()-8)
    var s = date.Format('YYYY-MM-DD HH:mm:ss')
    return s
  }

  praseStatus = status =>{
    switch(status){
      case -1:
        return '失败'
      case 0:
        return '等待中'
      case 1:
        return '发布中'
      case 2:
        return '发布中'
      case 3:
        return '成功'
    }
  }
  
  praseStatusMap = status =>{
    switch(status){
      case -1:
        return 'error'
      case 0:
        return 'default'
      case 1:
        return 'processing'
      case 2:
        return 'processing'
      case 3:
        return 'success'
    }
  }

  praseType = value => {
    switch(value){
      case 'BAIJIA':
        return "百家"
      case 'TOUTIAO':
        return "头条"
      case 'QIER':
        return "企鹅"
      case 'DAYU':
        return "大鱼"
    }
  }

  render() {
    // praseType = this.praseType
    var praseStatus = this.praseStatus
    var praseStatusMap = this.praseStatusMap
    const { rule: { tasks }, loading } = this.props;
    const { selectedRows, modalVisible } = this.state;
    var columns = []
    if (isMobile){
      columns = [
        {
          title: '标题',
          dataIndex: 'title',
          key: 'title',
          width: 200,
          render: (val,record) => <a href={record.url} target="_Blank">{record.title}</a>,
        },
        {
          title: '账号',
          dataIndex: 'accountusername',
          width: 50,
          render: (val,record) => <span>{"["+this.praseType(record.account.plat)+"]"+record.account.nick_name}</span>,
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: 65,
          render(val) {
            return <Badge status={praseStatusMap(val)} text={praseStatus(val)} />;
          },
        },
        {
          title: '结果',
          dataIndex: 'result',
          width: 70,
          render: val => <span>{val}</span>,
        },
        {
          title: '时间',
          dataIndex: 'create_time',
          key: 'create_time',
          width: 50,
          render: val => <span>{this.praseDate(val).substring(3,14)}</span>,
        },
        {
          title: '操作',  
          width: 40,
          render: (val , record) => (
            <span>
              <a onClick={()=> this.republish(record)}>{record.status == -1?'重新发布':''}</a>  
            </span>
          ),
        },
      ];
  
    }else{
      columns = [
        {
          title: '编号',
          dataIndex: 'id',
          width: 60,
          key : 'id',
        },
        {
          title: '标题',
          dataIndex: 'title',
          key: 'title',
          width: 330,
          render: (val,record) => <a href={record.url} target="_Blank">{record.title}</a>,
        },
        {
          title: '平台',
          dataIndex: 'accountplat',
          width: 60,
          render: (val,record) => <span>{this.praseType(record.account.plat)}</span>,
        },
        {
          title: '账号',
          dataIndex: 'accountusername',
          render: (val,record) => <span>{record.account.nick_name}</span>,
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: 90,
          filters: [
            {
              text: status[0],
              value: 0,
            },
            {
              text: status[1],
              value: 1,
            },
            {
              text: status[2],
              value: 2,
            },
            {
              text: status[3],
              value: -1,
            }
          ],
          onFilter: (value, record) => record.status.toString() === value,
          render(val) {
            return <Badge status={praseStatusMap(val)} text={praseStatus(val)} />;
          },
        },
        {
          title: '结果',
          dataIndex: 'result',
          width: 200,
          render: val => <span>{val}</span>,
        },
        {
          title: '发布时间',
          dataIndex: 'create_time',
          key: 'create_time',
          sorter: true,
          width: 100,
          render: val => <span>{this.praseDate(val)}</span>,
        },
        {
          title: '操作',  
          render: (val , record) => (
            <span>
              <a onClick={()=> this.republish(record)}>{record.status == -1?'重新发布':''}</a>  
            </span>
          ),
        },
      ];
  
    }
    
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
    };

    return (
      <div style={{ margin: '0 -46px 0' }}>
        <Card className={styles.card} bordered={false}>
          <div className={styles.tableList}>
          <div className={styles.tableListOperator}>
             <Button style={{ marginRight: 10}} type="primary" onClick={() => this.refresh()}>
                刷新
             </Button>
          </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={tasks}
              columns={columns}
              pagination={true}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </div>
    );
  }
}
